package org.example.springboot.common;

import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.io.IOException;

public class FileStorageService {

    private static final Path fileStorageLocation;

    static {
        fileStorageLocation = Paths.get("files").toAbsolutePath().normalize();
        try {
            Files.createDirectories(fileStorageLocation);
        } catch (IOException ex) {
            throw new RuntimeException("Could not create the directory where the uploaded files will be stored.", ex);
        }
    }

    public static String storeFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (fileName == null || fileName.contains("..")) {
            throw new RuntimeException("Sorry! Filename contains invalid path sequence " + fileName);
        }

        try {
            Path targetLocation = fileStorageLocation.resolve(fileName);
            // Copy file and replace existing one if it exists
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException ex) {
            throw new RuntimeException("Could not store file " + fileName + ". Please try again!", ex);
        }
    }

    public static Path getFilePath(String fileName) {
        return fileStorageLocation.resolve(fileName).normalize();
    }
}
